package com.xinchao.job.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xinchao.common.constant.BusinessConstant;
import com.xinchao.common.constant.CmccApiConstant;
import com.xinchao.common.dto.CityCmccInfoDTO;
import com.xinchao.common.dto.DeviceSimInfoTrafficDTO;
import com.xinchao.common.util.CmccApiUtils;
import com.xinchao.common.util.ListUtil;
import com.xinchao.job.service.CityCmccInfoService;
import com.xinchao.job.service.DeviceSimInfoService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 更新终端sim卡信息当月流量
 *
 * @author dxy
 * @date 2018/9/10 16:56
 */
@DisallowConcurrentExecution
public class SimMonthTrafficJob extends QuartzJobBean {
	private static Logger logger = LoggerFactory.getLogger(SimMonthTrafficJob.class);
	@Autowired
	private DeviceSimInfoService deviceSimInfoService;
	@Autowired
	private CityCmccInfoService cityCmccInfoService;

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		// 4.1.2.2.2 批量号码月流量查询
		String method = "triopi.member.dailyflow.realtime.batch.query";
		try {
			// 城市对应的集团编码，应用键对应值，密钥的MAP
			Map<String, CityCmccInfoDTO> cityCmccInfoMap = cityCmccInfoService.getCityCmccInfoMap();
			if (cityCmccInfoMap != null && cityCmccInfoMap.size() > 0) {
				Set<String> citySet = cityCmccInfoMap.keySet();
				for (String city : citySet) {
					// 获取城市对应的集团编码，应用键对应值，密钥
					CityCmccInfoDTO cityCmccInfoDTO = cityCmccInfoMap.get(city);
					String appKeyValue = cityCmccInfoDTO.getAppKey();
					String secrect = cityCmccInfoDTO.getSecrect();
					String groupCode = cityCmccInfoDTO.getGroupCode();
					// 获取终端sim卡信息总数
					Long count = deviceSimInfoService.countDeviceSimInfo(city);
					if (count != null && count > 0) {
						List<DeviceSimInfoTrafficDTO> trafficList = deviceSimInfoService.listDeviceSimInfoTraffic(city);
						if (CollectionUtils.isNotEmpty(trafficList)) {
							// 默认条数，也是移动允许的单次允许查询条数
							int rows = 100;
							List<List<DeviceSimInfoTrafficDTO>> limitAssignList = ListUtil.singleLimitAssign(trafficList, rows);
							for (int j = 0; j < limitAssignList.size(); j++) {
								// 将iccid拼接整字符串，用逗号隔开
								StringBuilder sb = new StringBuilder();
								for ( DeviceSimInfoTrafficDTO device : limitAssignList.get(j) ) {
									sb.append(device.getIccid()).append(",");
								}
								String iccids = sb.toString();
								iccids = iccids.substring(0,iccids.length()-1);
//								logger.info("updateDeviceSimInfoMonthTraffic_iccids: " + iccids);
								// 将iccidSb的长度清零，重复使用
								sb.setLength(0);
								// 获取sim卡当月流量使用情况
								String data = CmccApiUtils.bachQuery(method, iccids, true, null, appKeyValue, secrect, groupCode);
								// 解析返回报文，批量更新
								batchSetMonthTraffic(data);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceSimInfoSchedule updateDeviceSimInfoMonthTraffic 更新终端sim卡信息当月流量预警失败：" + e.getMessage());
		}
	}

	private void batchSetMonthTraffic(String data) {
//		logger.info(">> updateDeviceSimInfoMonthTraffic.CmccApiUtils.bachQuery: " + data);
		if (StringUtils.isBlank(data)) {
			logger.error("DeviceSimInfoSchedule updateDeviceSimInfoMonthTraffic 更新终端sim卡信息当月流量预警失败： 接口返回参数为空");
			return;
		}
		// 转化为JSONObject
		JSONObject dataJsonObj = JSON.parseObject(data);
		// 获取msisdnList，以下代码是解析JSON数据并将解析出的数据存入数据
		JSONObject msisdnJsonObj = dataJsonObj.getJSONObject(CmccApiConstant.JSON_KEY_MSISDN_INFO_LIST);
		JSONArray jsonArray = msisdnJsonObj.getJSONArray(CmccApiConstant.JSON_KEY_LIST);
		if (jsonArray != null && jsonArray.size() > 0) {
			List<DeviceSimInfoTrafficDTO> list = new ArrayList<>();
			for (int j = 0; j < jsonArray.size(); j++) {
				JSONObject arrayJsonObj = jsonArray.getJSONObject(j);
				String iccid = arrayJsonObj.getString(CmccApiConstant.JSON_KEY_ICCID);
				JSONObject apnJsonObj = arrayJsonObj.getJSONObject(CmccApiConstant.JSON_KEY_APN_LIST);
				JSONArray apnJsonArray = apnJsonObj.getJSONArray(CmccApiConstant.JSON_KEY_LIST);
				double monthFlow = 0D;
				if (apnJsonArray != null && apnJsonArray.size() > 0) {
					for (int k = 0; k < apnJsonArray.size(); k++) {
						JSONObject usedJsonObj = apnJsonArray.getJSONObject(k);
						// 如果pkgInfoList的list列表列的内容不为空，就统计流量
						JSONObject pkgInfoJsonObj = usedJsonObj.getJSONObject(CmccApiConstant.JSON_KEY_PKG_INFO_LIST);
						JSONArray pkgInfoJsonArray = pkgInfoJsonObj.getJSONArray(CmccApiConstant.JSON_KEY_LIST);
						if (pkgInfoJsonArray == null || pkgInfoJsonArray.size() == 0) {
							continue;
						}
						double usedFlow = usedJsonObj.getDoubleValue(CmccApiConstant.JSON_KEY_USED_FLOW);
						monthFlow = monthFlow + usedFlow;
					}
				}
				DeviceSimInfoTrafficDTO trafficDTO = new DeviceSimInfoTrafficDTO();
				trafficDTO.setIccid(iccid);
				trafficDTO.setCurrentMonthTraffic(monthFlow + BusinessConstant.DATA_UNIT_M);
				list.add(trafficDTO);
			}
			// 将当月流量数据保存至数据库
			if (CollectionUtils.isNotEmpty(list)) {
				deviceSimInfoService.updateDeviceSimInfoMonthTrafficBatch(list);
//				for (DeviceSimInfoTrafficDTO dto : list) {
//					deviceSimInfoService.updateDeviceSimInfoMonthTraffic(dto);
//				}
			}
		}
	}

	public static void main(String[] args) {
		System.out.println(104L / 103L);
	}
}
